package com.mayikt.member.impl.manage;

import com.mayikt.member.impl.entitydo.UserLoginLogDo;
import com.mayikt.member.impl.mapper.UserLoginLogMapper;
import com.mayikt.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
@Slf4j
public class AsyncLoginLogManage {

    @Autowired
    private UserLoginLogMapper userLoginLogMapper;

    /**
     * 记录登录日志
     * 1.根据 渠道和userid 查询记录
     * 2.更新登录记录的有效性，并从redis删除token
     * 3.保存最新的登录记录
     */
    @Async
    public void loginLog(Long userId, String loginIp, Date loginTime, String loginToken, String channel, String equipment) {
        // 1. 根据当前的渠道+userid+可用 查询 该用户是否已经登陆过
        UserLoginLogDo userLoginLogDo = userLoginLogMapper.selectByUserIdAndLoginType(userId, channel);
        // 2. 如果没有查询到记录情况下  如果能够查询呢
        if (userLoginLogDo != null) {
            // 原来token
            String oldToken = userLoginLogDo.getLoginToken();
            // 更新数据库token状态
            int result = userLoginLogMapper.updateUserTokenNotQuipment(oldToken);
            // 从redis删除该token
            if (result > 0) {
                TokenUtil.delToken(oldToken);
            }
        }
        // 插入最新的token到数据库中
        UserLoginLogDo newUserLoginLogDo = new UserLoginLogDo(userId, loginIp, loginTime, loginToken, channel, equipment);
        userLoginLogMapper.insertUserLoginLog(newUserLoginLogDo);
    }
}
